// noipNOi 题解
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2e5 + 5;
int n, m;
int type[MAXN]; // 1/2/3
char str[MAXN];

struct Node {
  int i, j, d;
};
int dis[MAXN][4];   // (i, j, d)
bool used[MAXN][4]; // (i, j, d)

int ID(int i, int j) { return (i - 1) * m + j; }

const int dx[4] = {0, 1, -1, 0};
const int dy[4] = {1, 0, 0, -1};

inline void Solve() {
  scanf("%d%d", &n, &m);
  // (i,j) -> (i-1)*n+j
  for (int i = 1; i <= n; ++i) {
    scanf("%s", str + 1);
    for (int j = 1; j <= m; ++j) {
      type[ID(i, j)] = str[j] - 'A';
    }
  }

  for (int i = 1; i <= n * m + 1; ++i) {
    for (int j = 0; j <= 3; ++j) {
      dis[i][j] = 1e9;
      used[i][j] = 0;
    }
  }

  // 起点: (1, 1, 0)
  dis[ID(1, 1)][0] = 0;
  deque<Node> q;
  q.push_back({1, 1, 0});
  while (!q.empty()) {
    auto [i, j, d] = q.front();
    // 将要到达 (i,j)，进入方向是 d
    q.pop_front();
    if (used[ID(i, j)][d])
      continue;
    used[ID(i, j)][d] = 1;

    for (int ntype = 0; ntype <= 2; ++ntype) {
      int dd = d ^ ntype;
      int ii = i + dx[dd];
      int jj = j + dy[dd];
      int c = (type[ID(i, j)] != ntype);

      if ((ii >= 1 && ii <= n && jj >= 1 && jj <= m) ||
          (ii == n && jj == m + 1)) {
        if (dis[ID(ii, jj)][dd] > dis[ID(i, j)][d] + c) {
          dis[ID(ii, jj)][dd] = dis[ID(i, j)][d] + c;
          if (c == 0)
            q.push_front({ii, jj, dd});
          else
            q.push_back({ii, jj, dd});
        }
      }
    }
  }
  printf("%d\n", dis[ID(n, m + 1)][0]);
}

int main() {
  int T;
  scanf("%d", &T);
  while (T--)
    Solve();
  return 0;
}